﻿CREATE PROCEDURE [maint].[PurgeJobHistory]
AS
BEGIN
	DECLARE @purge_range_in_months int;
	SET @purge_range_in_months = config.GetInstanceSetting('JobHistoryPurgeThreshold');
	IF(@purge_range_in_months IS NULL)
	BEGIN
		RAISERROR('Job History Purge Threshold has not been configured. Unable to purge job history.',16,1);
	END
	
	DECLARE @purge_date datetime;
	SET @purge_date = DATEADD(MONTH,-@purge_range_in_months,GETDATE());

	DECLARE @rc INT;
	EXEC @rc = msdb.dbo.sp_purge_jobhistory  @oldest_date = @purge_date;
	PRINT(N'Job history older than ' + CAST(@purge_date AS varchar) + ' has been purged');
	IF(@rc <> 0)
	BEGIN
		RAISERROR('Failed to purge job history',16,1);
	END
END